package com.cloud.mybatis.config;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.BaseMultiTableInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.cloud.core.entity.permit.UserDeptRoleScope;
import lombok.*;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.update.Update;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 数据权限处理器
 *
 * @author hubin
 * @since 3.5.2
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@SuppressWarnings({"rawtypes"})
public class MyDataPermissionInterceptor extends BaseMultiTableInnerInterceptor implements InnerInterceptor {
    private DataPermissionHandler dataPermissionHandler;

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        if (InterceptorIgnoreHelper.willIgnoreDataPermission(ms.getId())) {
            return;
        }
        PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
        mpBs.sql(parserSingle(mpBs.sql(), ms.getId()));
    }

    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
        MappedStatement ms = mpSh.mappedStatement();
        SqlCommandType sct = ms.getSqlCommandType();
        if (sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) {
            if (InterceptorIgnoreHelper.willIgnoreDataPermission(ms.getId())) {
                return;
            }
            PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();
            mpBs.sql(parserMulti(mpBs.sql(), ms.getId()));
        }
    }

    @Override
    protected void processSelect(Select select, int index, String sql, Object obj) {
        if (dataPermissionHandler instanceof MultiDataPermissionHandler) {
            // 参照 com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor.processSelect 做的修改
            final String whereSegment = (String) obj;
            //===================dhaigang 添加===================================

            assertCond(obj, select);
            //======================================================
            processSelectBody(select.getSelectBody(), whereSegment);
            List<WithItem> withItemsList = select.getWithItemsList();
            if (!CollectionUtils.isEmpty(withItemsList)) {
                withItemsList.forEach(withItem -> processSelectBody(withItem, whereSegment));
            }
        } else {
            // 兼容原来的旧版 DataPermissionHandler 场景
            SelectBody selectBody = select.getSelectBody();
            if (selectBody instanceof PlainSelect) {
                this.setWhere((PlainSelect) selectBody, (String) obj);
            } else if (selectBody instanceof SetOperationList) {
                SetOperationList setOperationList = (SetOperationList) selectBody;
                List<SelectBody> selectBodyList = setOperationList.getSelects();
                selectBodyList.forEach(s -> this.setWhere((PlainSelect) s, (String) obj));
            }
        }
    }

    @SneakyThrows
    private void assertCond(Object obj, Select select) {
        LinkedHashMap<String,Object> permit = LoginHolder.getRoleScope();
        if(ObjectUtil.isNull(permit)){
            return;
        }
        if (permit.get("dataScope").equals("0")) {
            return;
        }
        PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
        Expression sqlSegment = plainSelect.getWhere();

        if (LoginHolder.mapperFunSet.contains(obj.toString()) && !permit.get("dataScope").equals("4")) {

            String tableL = plainSelect.getFromItem().toString();
            String[] tableA = tableL.split(" ");
            Table tableLeft;
            if (tableA.length > 1) {
                tableLeft = new Table(tableA[0]).withAlias(new Alias(tableA[1], true));
            } else {
                tableLeft = new Table(tableA[0]).withAlias(new Alias("permission", true));
            }
            String[] split = tableL.split("\\.");
            Table deptTable;
            if (split.length == 1) {
                deptTable = new Table("sys_dept").withAlias(new Alias("permit", true));
            }else {
                deptTable = new Table(split[0]+"."+split[1]+".sys_dept").withAlias(new Alias("permit", true));
            }

            Join deptJoin = new Join();
            deptJoin.withInner(true);
            deptJoin.withRightItem(deptTable);
            EqualsTo equalsTo = new EqualsTo();
            equalsTo.setLeftExpression(new Column(tableLeft, "dept_id"));
            equalsTo.setRightExpression(new Column(deptTable, "dept_id"));

            List<Expression> exList = new ArrayList<>();
            exList.add(equalsTo);
            deptJoin.setOnExpressions(exList);
            List<Join> list = plainSelect.getJoins();
            if(list==null ){
                list = new ArrayList<>();
            }
            list.add(deptJoin);
            plainSelect.setJoins(list);

            if (permit.get("dataScope").equals("1")) {
                Expression expression = CCJSqlParserUtil.parseExpression("permit.dept_id = " + permit.get("deptCode"));
                Expression expression2 = CCJSqlParserUtil.parseExpression("find_in_set("+permit.get("deptCode")+" ,permit.ancestors  ) ");
                Parenthesis parenthesis = new Parenthesis(new OrExpression(expression, expression2));
                plainSelect.setWhere(new AndExpression(sqlSegment, parenthesis))  ;
            }
            if (permit.get("dataScope").equals("2")) {
                Expression expression = CCJSqlParserUtil.parseExpression("permit.dept_id = " + permit.get("deptCode"));
                Parenthesis parenthesis = new Parenthesis(expression);
                plainSelect.setWhere(new AndExpression(sqlSegment, parenthesis));
            }
            if (permit.get("dataScope").equals("3")) {
                List<String> p = (List<String>) permit.get("permits");
                StringBuffer sb = new StringBuffer();
                sb.append("(");
                for(int i=0;i<p.size();i++){

                    sb.append(p.get(i));
                    if(i!=p.size()-1){
                        sb.append(",");
                    }
                }
                sb.append(")");
                Expression expression = CCJSqlParserUtil.parseExpression("permit.dept_id in " + sb.toString());
                Parenthesis parenthesis = new Parenthesis(expression);
                plainSelect.setWhere(new AndExpression(sqlSegment, parenthesis));
            }
        }
        if (LoginHolder.mapperFunSet.contains(obj.toString()) && permit.get("dataScope").equals("4")) {
            String tableL = plainSelect.getFromItem().toString();
            String[] tableA = tableL.split(" ");
            Expression expression;
            if (tableA.length > 1) {
                expression = CCJSqlParserUtil.parseExpression(tableA[1] + ".create_user = " + permit.get("userId"));
            } else {
                expression = CCJSqlParserUtil.parseExpression(tableA[0] + ".create_user =" + permit.get("userId"));

            }
            plainSelect.setWhere(  new AndExpression(sqlSegment,  expression));


        }

       // genWhere(  plainSelect);
    }


    /**
     * 设置 where 条件
     *
     * @param plainSelect  查询对象
     * @param whereSegment 查询条件片段
     */
    @SneakyThrows
    protected void setWhere(PlainSelect plainSelect, String whereSegment) {
        // 兼容旧版的数据权限处理
        final Expression sqlSegment = dataPermissionHandler.getSqlSegment(plainSelect.getWhere(), whereSegment);


        if (null != sqlSegment) {
            plainSelect.setWhere(sqlSegment);
        }
    }

    /**
     * update 语句处理
     */
    @Override
    protected void processUpdate(Update update, int index, String sql, Object obj) {
        final Expression sqlSegment = getUpdateOrDeleteExpression(update.getTable(), update.getWhere(), (String) obj);
        if (null != sqlSegment) {
            update.setWhere(sqlSegment);
        }
    }

    /**
     * delete 语句处理
     */
    @Override
    protected void processDelete(Delete delete, int index, String sql, Object obj) {
        final Expression sqlSegment = getUpdateOrDeleteExpression(delete.getTable(), delete.getWhere(), (String) obj);
        if (null != sqlSegment) {
            delete.setWhere(sqlSegment);
        }
    }

    protected Expression getUpdateOrDeleteExpression(final Table table, final Expression where, final String whereSegment) {
        if (dataPermissionHandler instanceof MultiDataPermissionHandler) {
            return andExpression(table, where, whereSegment);
        } else {
            // 兼容旧版的数据权限处理
            return dataPermissionHandler.getSqlSegment(where, whereSegment);
        }
    }

    @Override
    public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) {
        // 只有新版数据权限处理器才会执行到这里
        final MultiDataPermissionHandler handler = (MultiDataPermissionHandler) dataPermissionHandler;
        return handler.getSqlSegment(table, where, whereSegment);
    }
}
